/*=============================================================================

  Library: CFS

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

=============================================================================*/

#include "CFSPlugin_p.h"
#include "CFSPluginContext.h"
#include "CFSPluginContext_p.h"
#include "CFSPluginFrameworkContext_p.h"

#include "CFSServices_p.h"
#include "CFSServiceRegistration.h"
#include "CFSServiceReference.h"
#include "CFSServiceReference_p.h"

#include <stdexcept>

//----------------------------------------------------------------------------
CFSPluginContextPrivate::CFSPluginContextPrivate(CFSPluginPrivate* plugin)
  : plugin(plugin)
{}

//----------------------------------------------------------------------------
void CFSPluginContextPrivate::isPluginContextValid() const
{
  if (!plugin) {
    throw CFSIllegalStateException("This plugin context is no longer valid");
  }
}

//----------------------------------------------------------------------------
void CFSPluginContextPrivate::invalidate()
{
  plugin = 0;
}

//----------------------------------------------------------------------------
CFSPluginContext::CFSPluginContext(CFSPluginPrivate* plugin)
  : d_ptr(new CFSPluginContextPrivate(plugin))
{}

//----------------------------------------------------------------------------
CFSPluginContext::~CFSPluginContext()
{
  Q_D(CFSPluginContext);
  delete d;
}

//----------------------------------------------------------------------------
QVariant CFSPluginContext::getProperty(const QString& key) const
{
  Q_D(const CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->fwCtx->props.value(key);
}

//----------------------------------------------------------------------------
QSharedPointer<CFSPlugin> CFSPluginContext::getPlugin() const
{
  Q_D(const CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->q_func();
}

//----------------------------------------------------------------------------
QSharedPointer<CFSPlugin> CFSPluginContext::getPlugin(long id) const
{
  Q_D(const CFSPluginContext);
  return d->plugin->fwCtx->plugins->getPlugin(id);
}

//----------------------------------------------------------------------------
QList<QSharedPointer<CFSPlugin> > CFSPluginContext::getPlugins() const
{
  Q_D(const CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->fwCtx->plugins->getPlugins();
}

//----------------------------------------------------------------------------
QSharedPointer<CFSPlugin> CFSPluginContext::installPlugin(const QUrl& location, QIODevice* in)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->fwCtx->plugins->install(location, in);
}

//----------------------------------------------------------------------------
QFileInfo CFSPluginContext::getDataFile(const QString& filename)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  QDir dataRoot(d->plugin->getDataRoot().absolutePath());
  if (!dataRoot.exists())
  {
    if (!dataRoot.mkpath(dataRoot.absolutePath()))
    {
      qWarning() << "Could not create persistent storage area:" << dataRoot.absolutePath();
    }
  }
  return QFileInfo(dataRoot.absolutePath() + '/' + filename);
}

//----------------------------------------------------------------------------
CFSServiceRegistration CFSPluginContext::registerService(const QStringList& clazzes, QObject* service, const CFSDictionary& properties)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->fwCtx->services->registerService(d->plugin, clazzes, service, properties);
}

//----------------------------------------------------------------------------
CFSServiceRegistration CFSPluginContext::registerService(const char* clazz, QObject* service, const CFSDictionary& properties)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  QStringList clazzes;
  clazzes.append(clazz);
  return d->plugin->fwCtx->services->registerService(d->plugin, clazzes, service, properties);
}

//----------------------------------------------------------------------------
QList<CFSServiceReference> CFSPluginContext::getServiceReferences(const QString& clazz, const QString& filter)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->fwCtx->services->get(clazz, filter, 0);
}

//----------------------------------------------------------------------------
CFSServiceReference CFSPluginContext::getServiceReference(const QString& clazz)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  return d->plugin->fwCtx->services->get(d->plugin, clazz);
}

//----------------------------------------------------------------------------
QObject* CFSPluginContext::getService(const CFSServiceReference& reference)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();

  if (!reference)
  {
    throw CFSInvalidArgumentException("Default constructed CFSServiceReference is not a valid input to getService()");
  }
  CFSServiceReference internalRef(reference);
  return internalRef.d_func()->getService(d->plugin->q_func());
}

//----------------------------------------------------------------------------
bool CFSPluginContext::ungetService(const CFSServiceReference& reference)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  CFSServiceReference ref = reference;
  return ref.d_func()->ungetService(d->plugin->q_func(), true);
}

//----------------------------------------------------------------------------
bool CFSPluginContext::connectPluginListener(const QObject* receiver, const char* slot,
                                             Qt::ConnectionType type)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  // TODO check permissions for a direct connection
  if (type == Qt::DirectConnection || type == Qt::BlockingQueuedConnection)
  {
    return receiver->connect(&(d->plugin->fwCtx->listeners), SIGNAL(pluginChangedDirect(CFSPluginEvent)), slot, type);
  }
  else if (type == Qt::QueuedConnection)
  {
    return receiver->connect(&(d->plugin->fwCtx->listeners), SIGNAL(pluginChangedQueued(CFSPluginEvent)), slot, type);
  }
  else
  {
    throw CFSInvalidArgumentException("Only Qt::DirectConnection, Qt::QueuedConnection, or Qt::BlockingQueuedConnection are allowed as type argument.");
  }
}

//----------------------------------------------------------------------------
void CFSPluginContext::disconnectPluginListener(const QObject *receiver, const char* slot)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();

  QObject::disconnect(&(d->plugin->fwCtx->listeners), SIGNAL(pluginChangedDirect(CFSPluginEvent)), receiver, slot);
  QObject::disconnect(&(d->plugin->fwCtx->listeners), SIGNAL(pluginChangedQueued(CFSPluginEvent)), receiver, slot);
}

//----------------------------------------------------------------------------
bool CFSPluginContext::connectFrameworkListener(const QObject* receiver, const char* slot, Qt::ConnectionType type)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  // TODO check permissions for a direct connection
  return receiver->connect(&(d->plugin->fwCtx->listeners), SIGNAL(frameworkEvent(CFSPluginFrameworkEvent)), slot, type);
}

//----------------------------------------------------------------------------
void CFSPluginContext::disconnectFrameworkListener(const QObject *receiver, const char* slot)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();

  QObject::disconnect(&(d->plugin->fwCtx->listeners), SIGNAL(frameworkEvent(CFSPluginFrameworkEvent)), receiver, slot);
}

//----------------------------------------------------------------------------
void CFSPluginContext::connectServiceListener(QObject* receiver, const char* slot,
                                             const QString& filter)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  d->plugin->fwCtx->listeners.addServiceSlot(getPlugin(), receiver, slot, filter);
}

//----------------------------------------------------------------------------
void CFSPluginContext::disconnectServiceListener(QObject* receiver,
                                                const char* slot)
{
  Q_D(CFSPluginContext);
  d->isPluginContextValid();
  d->plugin->fwCtx->listeners.removeServiceSlot(getPlugin(), receiver, slot);
}
